package com.newpage.module_gather.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.daquexian.flexiblerichtextview.FlexibleRichTextView;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.newpage.module_gather.R;
import com.newpage.module_gather.R2;
import com.newpage.module_gather.adapter.CommonExplainAdapter;
import com.newpage.module_gather.adapter.QuestionNoAdapter;
import com.newpage.module_gather.contract.RevisionDetailCon;
import com.newpage.module_gather.presenter.RevisionDetailPre;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.request.RevisionQuestionReq;
import com.wetao.lib_common.bean.response.ExplainBean;
import com.wetao.lib_common.bean.response.RevisionExamQuestionInfo;
import com.wetao.lib_common.finalParam.QuestionType;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.QuestionRevisionItem;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.BaseEvent;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FormulaUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.OptionStr;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.video.AudioPlayerManager;
import com.wetao.lib_common.view.CustomPopWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author: zhouyh
 * created on: 2021/6/21 4:25 下午
 * description:错题订正详情页
 */
@Route(path = ConstantArouter.PATH_GATHER_REVISIONDETAILAILACTIVITY)
public class RevisionDetailActivity extends BaseActivity<RevisionDetailCon.View, RevisionDetailPre> implements RevisionDetailCon.View,
        AudioPlayerManager.CallbackPlay {

    @Autowired
    int examId;  //试卷id
    @Autowired
    int studentExamId;  //学生考试id
    @Autowired
    String examName;  //试题名称
    @Autowired
    int isRevision;  //是否订正


    @BindView(R2.id.sv_revision)
    ScrollView sv_revision;

    //题号视图
    @BindView(R2.id.iv_revision_question_left)
    ImageView iv_revision_question_left;
    @BindView(R2.id.iv_revision_question_right)
    ImageView iv_revision_question_right;
    @BindView(R2.id.rv_revision_question_no)
    RecyclerView rv_revision_question_no;


    @BindView(R2.id.frtv_exam_content)
    FlexibleRichTextView frtv;

    /**
     * 试题详解视图
     */
    @BindView(R2.id.ll_revision_detail_explain)
    LinearLayout ll_revision_detail_explain;
    @BindView(R2.id.ll_pop_teacher)
    LinearLayout ll_pop_teacher;
    @BindView(R2.id.iv_popDowUp_teacher)
    ImageView iv_popDownUp;
    @BindView(R2.id.tv_pop_teacher_name)
    TextView tv_pop_teacher_name;

    //视频视图
    @BindView(R2.id.ll_video)
    LinearLayout ll_video;
    @BindView(R2.id.tv_video)
    TextView tv_video;

    //音频视图
    @BindView(R2.id.ll_audio)
    LinearLayout ll_audio;
    @BindView(R2.id.iv_audio_play_or_pause)
    ImageView iv_audio_play_or_pause;
    @BindView(R2.id.tv_audio_time)
    TextView tv_audio_time;
    @BindView(R2.id.rsb_audio_progress)
    RangeSeekBar rsb_audio_progress;
    @BindView(R2.id.iv_voice_play_or_pause)
    ImageView iv_voice_play_or_pause;

    //掌握程度视图
    @BindView(R2.id.ll_understand)
    LinearLayout ll_understand;
    @BindView(R2.id.iv_understand)
    ImageView iv_understand;
    @BindView(R2.id.tv_understand)
    TextView tv_understand;
    @BindView(R2.id.ll_no_understand)
    LinearLayout ll_no_understand;
    @BindView(R2.id.iv_no_understand)
    ImageView iv_no_understand;
    @BindView(R2.id.tv_no_understand)
    TextView tv_no_understand;

    //我的答案视图
    @BindView(R2.id.frtv_revision_my_answer)
    FlexibleRichTextView frtv_my_answer;
    //正确答案
    @BindView(R2.id.frtv_revision_standard_answer)
    FlexibleRichTextView frtv_revision_standard_answer;


    //底部视图
    @BindView(R2.id.tv_next_question)
    TextView tv_next_question;
    @BindView(R2.id.tv_write_and_speak)
    TextView tv_write_and_speak;


    //语音批注视图
    @BindView(R2.id.tv_no_comment)
    TextView tv_no_comment;
    @BindView(R2.id.ll_phonetic_audio)
    LinearLayout ll_phonetic_audio;
    @BindView(R2.id.iv_phonetic_play_or_pause)
    ImageView iv_phonetic_play_or_pause;
    @BindView(R2.id.tv_phonetic_time)
    TextView tv_phonetic_time;
    @BindView(R2.id.rsb_phonetic_progress)
    RangeSeekBar rsb_phonetic_progress;
    @BindView(R2.id.iv_comment_voice)
    ImageView iv_comment_voice;

    @BindView(R2.id.tv_my_score)
    TextView tv_my_score;
    @BindView(R2.id.tv_question_score)
    TextView tv_question_score;
    @BindView(R2.id.frtv_answer_explain)
    FlexibleRichTextView frtv_answer_explain;

    @BindView(R2.id.ll_revision_other_content)
    LinearLayout ll_revision_other_content;
    @BindView(R2.id.ll_revision_detail_screen)
    LinearLayout ll_revision_detail_screen;
    @BindView(R2.id.tv_revision_detail_screen)
    TextView tv_revision_detail_screen;
    @BindView(R2.id.tv_revision_detail_content)
    TextView tv_revision_detail_content;


    //说写订正实体
    private QuestionRevisionItem item;

    private int revisionAction = 0; //订正接口操作   0删除操作  1提交订正操作

    //订正内容的实体
    private RevisionQuestionReq.RevisionBean revisionBean;


    private List<RevisionExamQuestionInfo.Data.QuestionListBean> questionListBeans = new ArrayList<>();
    private RevisionExamQuestionInfo.Data.QuestionListBean curQuestion;


    /**
     * 错题订正的数据集合
     */
    private List<RevisionQuestionReq.RevisionBean> vos = new ArrayList<>();


    /**
     * 标题列表
     */
    private int questionNo = 0;
    private QuestionNoAdapter questionNoAdapter;

    //讲解弹框
    private RecyclerView rcy_pop_teacher;
    private CommonExplainAdapter explainTeacherAdapter;
    //老师讲解集合
    private List<ExplainBean> explainListBeans = new ArrayList<>();
    private ExplainBean curExplainBean; //当前的讲解老师
    private CustomPopWindow popWindowTeacher;


    private Boolean isExplainAudio; //判断是否是试题讲解音频  true 讲解   false 批注
    //播放音频
    private String audioPath;
    private boolean startTimer = false; //是否开始播放批注
    private AudioManager audioManager;
    private float rsb_fromUser_value = 0;
    private long mDuration;
    //最大音量
    int maxVolume;
    //当前音量
    int currentVolume;

    private Integer questionId;
    private Integer studentExamAnswerId;

    //说写订正地址
    private String revisionContent;
    //说写订正时长
    private String revisionTime;


    @Override
    public int getLayoutId() {
        return R.layout.gather_activity_revision_detail;
    }

    @Override
    public RevisionDetailPre createPresenter() {
        return new RevisionDetailPre(this);
    }

    @Override
    public RevisionDetailCon.View createView() {
        return this;
    }

    @SuppressLint("InvalidWakeLockTag")
    @Override
    public void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initTitleLayout();
        setTvTitle(examName, true);
        initLongClickEvent();
        initQuestionNoAdapter();
        initAudioPlay();
        initVolume();
        listenerRangeChanged();
        createTeacherPop();
        getRevisionDetailReq();

    }


    private void initLongClickEvent() {
        tv_write_and_speak.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (curQuestion.getIsRevision() != null && curQuestion.getIsRevision() == 1) {
                    showDeleteRevisionDialog();
                }
                return true;
            }
        });
    }

    private void initQuestionNoAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rv_revision_question_no.setLayoutManager(layoutManager);
        questionNoAdapter = new QuestionNoAdapter(this);
        questionNoAdapter.setOnItemClickListener(new QuestionNoAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                questionNo = position;
                updateView(questionListBeans.get(position));
            }
        });
        rv_revision_question_no.setAdapter(questionNoAdapter);
    }


    /**
     * 初始化播放服务
     */
    private void initAudioPlay() {

        AudioPlayerManager.getInstance(this).setCallbackPlay(this);
        AudioPlayerManager.getInstance(this).playWithCompletionListener(audioPath, new Player.EventListener() {
            @Override
            public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
                LogUtils.i("onTimelineChanged start");
            }

            @Override
            public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
                LogUtils.i("onTracksChanged start");
            }

            @Override
            public void onLoadingChanged(boolean isLoading) {
                LogUtils.i("onLoadingChanged start");
            }

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                LogUtils.i("onPlayerStateChanged start platbackState is " + playbackState + "===" + playWhenReady);
                if (AudioPlayerManager.getInstance(RevisionDetailActivity.this).isPlaying() && !startTimer) {
                    startTimer = true;
                    AudioPlayerManager.getInstance(RevisionDetailActivity.this).updateSeekBar();
                    mDuration = AudioPlayerManager.getInstance(RevisionDetailActivity.this).getMediaPlayer().getDuration();

                }
                if (playbackState == Player.STATE_ENDED) {
                    startTimer = false;
                    AudioPlayerManager.getInstance(RevisionDetailActivity.this).reset(0);
                    AudioPlayerManager.getInstance(RevisionDetailActivity.this).refreshPosition(true);
                    resetRangeSeekBar();
                }

                if (playbackState == Player.STATE_IDLE || playbackState == Player.STATE_ENDED) {
                    playWhenReady = false;
                }
                setPlayView(playWhenReady);
            }

            @Override
            public void onRepeatModeChanged(int repeatMode) {
                LogUtils.i("onRepeatModeChanged start");
            }

            @Override
            public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
                LogUtils.i("onShuffleModeEnabledChanged start");
            }

            @Override
            public void onPlayerError(ExoPlaybackException error) {
                LogUtils.i("onPlayerError start");
            }

            @Override
            public void onPositionDiscontinuity(int reason) {
                LogUtils.i("onPositionDiscontinuity start");
            }

            @Override
            public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
                LogUtils.i("onPlaybackParametersChanged start");
            }

            @Override
            public void onSeekProcessed() {
                LogUtils.i("onSeekProcessed start");
            }
        });
    }


    /**
     * 初始化音量
     */
    private void initVolume() {
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    /**
     * 音频拖动监听
     */
    private void listenerRangeChanged() {

        rsb_audio_progress.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if (isFromUser) {
                    LogUtils.i("rsb_video_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);
                    rsb_fromUser_value = leftValue;
                }

            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
                int cur = (int) (rsb_fromUser_value / view.getMaxProgress() * mDuration);
                LogUtils.e("onStopTrackingTouch cur ==" + cur);
                AudioPlayerManager.getInstance(RevisionDetailActivity.this).getMediaPlayer().seekTo(cur);
            }
        });

        rsb_phonetic_progress.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if (isFromUser) {
                    LogUtils.i("rsb_video_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);
                    rsb_fromUser_value = leftValue;
                }

            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
                int cur = (int) (rsb_fromUser_value / view.getMaxProgress() * mDuration);
                AudioPlayerManager.getInstance(RevisionDetailActivity.this).getMediaPlayer().seekTo(cur);

            }
        });
    }


    /**
     * 初始化老师讲解弹框
     */
    private void createTeacherPop() {

        View popView = LayoutInflater.from(this).inflate(R.layout.gather_teacher_pop, null);
        rcy_pop_teacher = popView.findViewById(R.id.rcy_pop_teacher);
        initPopRcyView();
        popWindowTeacher = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(popView)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .setOnDissmissListener(() -> iv_popDownUp.setImageResource(R.drawable.common_arrow_down)).create();
    }

    /**
     * 显示讲解弹框
     */
    private void showExplainPop() {
        popWindowTeacher.showAsDropDown(ll_pop_teacher, ll_pop_teacher.getWidth() / 2 - popWindowTeacher.getWidth() / 2, 14);
        iv_popDownUp.setImageResource(R.drawable.common_arrow_up);
    }

    /**
     * 初始化教材列表数据
     *
     * @param
     */
    private void initPopRcyView() {

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        explainTeacherAdapter = new CommonExplainAdapter(this);
        explainTeacherAdapter.setOnItemClickListener(new CommonExplainAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                if (explainListBeans != null && explainListBeans.size() > 0) {
                    ExplainBean bean = explainListBeans.get(position);
                    LogUtils.i("explain bean :" + bean.toString());
                    if (AudioPlayerManager.getInstance(RevisionDetailActivity.this).isPlaying()
                            && curExplainBean.getExplainType() != bean.getExplainType()
                            && (isExplainAudio != null && isExplainAudio == true)) {
                        onPlayOrPause();
                        setPlayView(false);
                    }
                    initExplainView(curExplainBean = bean);
                }
                popWindowTeacher.dissmiss();
            }
        });
        rcy_pop_teacher.setLayoutManager(mLayoutManager);
        rcy_pop_teacher.setAdapter(explainTeacherAdapter);
        rcy_pop_teacher.setOverScrollMode(View.OVER_SCROLL_NEVER);
    }

    /**
     * 错题详情数据请求
     */
    private void getRevisionDetailReq() {
        getPresenter().revisionExamQuestionList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                new String[]{"studentExamId"},
                new Object[]{studentExamId}), true, false);
    }

    /**
     * 试题讲解已懂未懂请求
     *
     * @return
     */
    private void updateUnderStandReq(String id, int isUnderstand) {
        getPresenter().updateUnderstand(ComUtil.getHashmapByStr(new String[]{"id", "isUndrestand"}, new String[]{id, String.valueOf(isUnderstand)}), false, false, isUnderstand);
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }


    /**
     * 处理数据
     */
    private void updateView(RevisionExamQuestionInfo.Data.QuestionListBean questionBean) {
        if (questionBean != null) {
            if (questionBean.getIsSingle() != null && questionBean.getIsSingle() == 0) {
                tv_revision_detail_content.setSelected(true);
                tv_revision_detail_screen.setSelected(false);
                ll_revision_detail_screen.setVisibility(View.VISIBLE);
            } else {
                ll_revision_detail_screen.setVisibility(View.GONE);
            }
            ll_revision_other_content.setVisibility(View.VISIBLE);

            sv_revision.scrollTo(0, 0);
            curQuestion = questionBean;
            LogUtils.e("updateView:" + JsonUtils.toJson(curQuestion));


            questionId = curQuestion.getQuestionId();
            studentExamAnswerId = curQuestion.getStudentExamAnswerId();


            //试题讲解视图
            explainTeacherAdapter.setData(questionBean.getExplainList());
            explainListBeans.clear();
            explainListBeans.addAll(questionBean.getExplainList());
            explainTeacherAdapter.setData(explainListBeans);
            if (explainListBeans.size() > 0) {
                initExplainView(curExplainBean = explainListBeans.get(0));
            } else {
                hideExplainView();
            }

            if (questionBean.getIsUndrestand() == null) {
                ll_no_understand.setSelected(false);
                iv_no_understand.setSelected(false);
                ll_understand.setSelected(false);
                iv_understand.setSelected(false);
            } else if (questionBean.getIsUndrestand() == 0) {
                ll_no_understand.setSelected(true);
                iv_no_understand.setSelected(true);
                ll_understand.setSelected(false);
                iv_understand.setSelected(false);
            } else if (questionBean.getIsUndrestand() == 1) {
                ll_no_understand.setSelected(false);
                iv_no_understand.setSelected(false);
                ll_understand.setSelected(true);
                iv_understand.setSelected(true);
            }


            //显示批注
            if (questionBean.getVoiceComment() != null) {
                tv_no_comment.setVisibility(View.GONE);
                ll_phonetic_audio.setVisibility(View.VISIBLE);
            } else {
                ll_phonetic_audio.setVisibility(View.GONE);
                tv_no_comment.setVisibility(View.VISIBLE);
            }


            //0代表套题未订正 1代表已提交过订正
            updateSubmitTextView(questionNo);

            updateRevisionTextView();

            //显示题目题干
            showFlexibleRichTextView(frtv, questionBean, questionNo);

            //显示答案
            String answerContent = questionBean.getDoodle() != null ? questionBean.getDoodle() : questionBean.getAnswerContent();
            if (answerContent!=null && questionBean.getQuestionType() != null && questionBean.getQuestionType() == QuestionType.QUESTIONTYPE_PANDUANTI) {
                if (answerContent.equals("F")) {
                    answerContent = "错";
                } else if (answerContent.equals("T")) {
                    answerContent = "对";
                }
            }
            showAnsweredTextView(frtv_my_answer, answerContent);

            tv_my_score.setText(String.format("我的得分：%s", questionBean.getMyScore() == null ? "0.0" : questionBean.getMyScore()));
            tv_question_score.setText(String.format("本题满分：%s", questionBean.getQuestionScore() == null ? "" : questionBean.getQuestionScore()));

            StringBuilder sbAnswer = new StringBuilder();
            for (String str : questionBean.getAnswers()) {
                sbAnswer.append(str);
            }
            String standardContent = sbAnswer.toString();
            if (questionBean.getQuestionType() != null && questionBean.getQuestionType() == QuestionType.QUESTIONTYPE_PANDUANTI) {
                if (standardContent.equals("F")) {
                    standardContent = "错";
                } else if (standardContent.equals("T")) {
                    standardContent = "对";
                }
            }
            showAnsweredTextView(frtv_revision_standard_answer, standardContent);

            showAnsweredTextView(frtv_answer_explain, questionBean.getExplain());


            /**
             * 停止音频
             */
            startTimer = false;
            if (AudioPlayerManager.getInstance(this).isPlaying()) {
                AudioPlayerManager.getInstance(RevisionDetailActivity.this).stop(true);
            }
            resetRangeSeekBar();

        }


    }

    private void resetRangeSeekBar() {
        isExplainAudio = null;
        iv_audio_play_or_pause.setImageResource(R.drawable.common_video_start);
        iv_phonetic_play_or_pause.setImageResource(R.drawable.common_video_start);
        rsb_audio_progress.setProgress(0);
        rsb_phonetic_progress.setProgress(0);
        if (curExplainBean != null) {
            tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(curExplainBean.getVideoTime() == null ? 0 : curExplainBean.getVideoTime() * 1000)));
        }
        if (curQuestion != null) {
            tv_phonetic_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(curQuestion.getVoiceCommentDuration() == null ? 0 : curQuestion.getVoiceCommentDuration() * 1000)));
        }

    }

    /**
     * 没有讲解内容时隐藏
     */
    private void hideExplainView() {
        ll_revision_detail_explain.setVisibility(View.GONE);
    }


    /**
     * 显示试题情景内容
     */
    private void showScreenContent() {
        showAnsweredTextView(frtv, curQuestion == null ? null : curQuestion.getQuestionScreen());
    }


    /**
     * 显示小题内容
     */
    private void showQuestionContent() {
        showFlexibleRichTextView(frtv, curQuestion, questionNo);
    }


    /**
     * 显示试题
     *
     * @param view
     * @param bean
     * @param questionNo
     */
    private void showFlexibleRichTextView(final FlexibleRichTextView view, RevisionExamQuestionInfo.Data.QuestionListBean bean, int questionNo) {
        view.resetTextView();

//        float f_size = getResources().getDimension(R.dimen.dp_15);
        if (bean != null) {
            final StringBuilder stringBuilder = new StringBuilder();
            String question = bean.getQuestion();
            if (!StringUtil.isEmpty(question)) {
                stringBuilder.append(String.format("%s. ", questionNo + 1));
                String temp = FormulaUtil.reLatex(question);
                stringBuilder.append(temp);
            }
            List<String> options = bean.getOptions();
            if (options != null && options.size() > 0) {
                int o_index = 0;
                for (String value : options) {
                    if (value != null && !StringUtil.isEmpty(value) && o_index < OptionStr.OPS.length) {
                        if (o_index > 0) {
                            stringBuilder.append("\r\n");
                        }
                        stringBuilder.append(OptionStr.OPS[o_index] + ". ");
                        stringBuilder.append(FormulaUtil.reLatex(value));
                        o_index++;
                    }
                }
            }
            LogUtils.i(stringBuilder.toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    view.setText(stringBuilder.toString());
                }
            });
        }
    }


    /**
     * 显示试题讲解试图
     *
     * @param bean
     */
    private void initExplainView(ExplainBean bean) {
        if (bean == null) return;
        ll_revision_detail_explain.setVisibility(View.VISIBLE);
        tv_pop_teacher_name.setText(bean.getExplainName());
        if (bean.getExplainType() != null) {
            if (bean.getExplainType() == Constants.TYPE_AUDIO) {
                ll_audio.setVisibility(View.VISIBLE);
                ll_video.setVisibility(View.GONE);
                tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(bean.getVideoTime() == null ? 0 : bean.getVideoTime() * 1000)));
            } else if (bean.getExplainType() == Constants.TYPE_VIDEO) {
                ll_audio.setVisibility(View.GONE);
                ll_video.setVisibility(View.VISIBLE);
                tv_video.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_video_mp4, 0, 0, 0);
                tv_video.setText(ComUtil.stringForTime(bean.getVideoTime() == null ? 0 : bean.getVideoTime() * 1000));
            } else if (bean.getExplainType() == Constants.TYPE_TRACK) {
                ll_audio.setVisibility(View.GONE);
                ll_video.setVisibility(View.VISIBLE);
                tv_video.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_video_track, 0, 0, 0);
                tv_video.setText(ComUtil.stringForTime(bean.getVideoTime() == null ? 0 : bean.getVideoTime() * 1000));
            }
        }


    }

    @Override
    public void revisionExamQuestionListResult(RevisionExamQuestionInfo resp) {
        if (resp.getData() != null) {
            questionListBeans.clear();
            questionListBeans.addAll(resp.getData().getQuestionList());
            if (questionListBeans.size() > 0) {
                questionNoAdapter.setQuestionData(questionListBeans);
                updateView(questionListBeans.get(questionNo));
            }
        }
    }

    @Override
    public void revisionExamQuestionListFail() {

    }


    @Override
    public void updateUnderstandSuccess(BaseResponse resp, Integer state) {
        questionListBeans.get(questionNo).setIsUndrestand(state);
    }

    @Override
    public void updateUnderstandFail() {

    }

    @Override
    public void revisionWrongQuestionResult(BaseResponse resp, boolean isSingle) {

        hideSubmitDialog();
        if (isSingle) {
            //单题提交
            if (revisionAction == 0) {
                questionListBeans.get(questionNo).setIsRevision(0);
                questionListBeans.get(questionNo).setRevisionContent("");
                questionListBeans.get(questionNo).setRevisionType(null);
                questionListBeans.get(questionNo).setRevisionTime(null);
                questionNoAdapter.setQuestionData(questionListBeans);
                curQuestion = questionListBeans.get(questionNo);
                deleteRevisionItem();
                ToastUtil.initToast("删除成功");
            } else {
                questionListBeans.get(questionNo).setIsRevision(1);
                questionListBeans.get(questionNo).setRevisionContent(revisionBean.getRevisionContent());
                questionListBeans.get(questionNo).setRevisionType(revisionBean.getRevisionType());
                questionListBeans.get(questionNo).setRevisionTime(revisionBean.getRevisionTime());
                questionNoAdapter.setQuestionData(questionListBeans);
                curQuestion = questionListBeans.get(questionNo);
                ToastUtil.initToast("订正成功");
            }
            updateRevisionTextView();
        } else {
            //套题提交，下标为题目数量 size - 1
            updateSubmitTextView(questionListBeans.size() - 1);
            ToastUtil.initToast("提交订正成功");
            finish();
        }
    }

    @Override
    public void revisionWrongQuestionFail(boolean isSingle) {
        hideSubmitDialog();
        if (isSingle) {
            if (revisionAction == 0) {
                ToastUtil.initToast("删除失败");
            } else {
                ToastUtil.initToast("提交失败");
            }
        } else {
            ToastUtil.initToast("提交订正失败");
        }
    }

    @OnClick({
            R2.id.ll_pop_teacher, R2.id.ll_video,
            R2.id.iv_audio_play_or_pause, R2.id.iv_voice_play_or_pause,R2.id.iv_comment_voice,
            R2.id.ll_understand, R2.id.ll_no_understand, R2.id.iv_back,
            R2.id.tv_next_question, R2.id.tv_write_and_speak,
            R2.id.iv_phonetic_play_or_pause, R2.id.iv_revision_question_left,
            R2.id.iv_revision_question_right, R2.id.tv_revision_detail_screen,
            R2.id.tv_revision_detail_content})
    public void onClick(View view) {
        int mId = view.getId();
        if (mId == R.id.ll_pop_teacher) {

            showExplainPop();

        } else if (mId == R.id.ll_video) {

            if (curExplainBean.getExplainType() == Constants.TYPE_VIDEO) {
                ARouter.getInstance().build(ConstantArouter.PATH_LECTURE_LECTUREVIDEOACTIVITY)
                        .withString("videoInfo", JsonUtils.toJson(curExplainBean))
//                        .withString("title", data.getData().getWrongSource())
                        .navigation();
            } else if (curExplainBean.getExplainType() == Constants.TYPE_TRACK) {
                ARouter.getInstance().build(ConstantArouter.PATH_LECTURE_LECTUREPLAYVIDEOEXPLAINACTIVITY)
                        .withString("explainName", curExplainBean.getExplainName())
                        .withString("explainUrl", curExplainBean.getExplainUrl())
                        .withInt("explainType", curExplainBean.getExplainType())
                        .withInt("videoTime", curExplainBean.getVideoTime() == null ? 0 : curExplainBean.getVideoTime())
                        .navigation();
            }

        } else if (mId == R.id.iv_audio_play_or_pause) {

            if (curExplainBean != null && curExplainBean.getExplainUrl() != null) {
                if (!curExplainBean.getExplainUrl().endsWith(Constants.VIDEO_FORMAT)) {
                    ToastUtil.initToast("该音频地址格式错误，无法播放");
                    return;
                }else{
                    playOrPause(iv_audio_play_or_pause, curExplainBean.getExplainUrl(), true);
                }
            }

        } else if (mId == R.id.iv_voice_play_or_pause || mId == R.id.iv_comment_voice) {

            if (currentVolume > 0) {
                currentVolume = 0;
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
            } else {
                currentVolume = maxVolume / 2;
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
            }
            if (iv_voice_play_or_pause.isSelected()) {
                iv_voice_play_or_pause.setSelected(false);
                iv_voice_play_or_pause.setImageResource(R.drawable.common_voice);

                iv_comment_voice.setSelected(false);
                iv_comment_voice.setImageResource(R.drawable.common_voice);

            } else {
                iv_voice_play_or_pause.setSelected(true);
                iv_voice_play_or_pause.setImageResource(R.drawable.common_voice_close);

                iv_comment_voice.setSelected(true);
                iv_comment_voice.setImageResource(R.drawable.common_voice_close);
            }


        } else if (mId == R.id.ll_understand) {

            ll_no_understand.setSelected(false);
            iv_no_understand.setSelected(false);
            ll_understand.setSelected(true);
            iv_understand.setSelected(true);
            updateUnderStandReq(String.valueOf(curQuestion.getStudentExamAnswerId()), 1);

        } else if (mId == R.id.ll_no_understand) {

            ll_no_understand.setSelected(true);
            iv_no_understand.setSelected(true);
            ll_understand.setSelected(false);
            iv_understand.setSelected(false);
            updateUnderStandReq(String.valueOf(curQuestion.getStudentExamAnswerId()), 0);

        } else if (mId == R.id.iv_back) {
            finish();

        } else if (mId == R.id.tv_next_question) {

            if (questionNo == questionListBeans.size() - 1) {
                showSubmitRevisionDialog();
            } else {
                questionNo = checkNextWrongQuestionIndex();
                rv_revision_question_no.scrollToPosition(questionNo);
                questionNoAdapter.setCheckPos(questionNo);
                questionNoAdapter.notifyDataChanged();
                updateView(questionListBeans.get(questionNo));
            }

        } else if (mId == R.id.tv_write_and_speak) {
            if (tv_write_and_speak.isSelected()) {
                ARouter.getInstance().build(ConstantArouter.PATH_GATHER_GATHERRPLAYREVISIONACTIVITY)
                        .withInt("examId", examId)
                        .withInt("type", Constants.TYPE_1)
                        .withString("revisionUrl", revisionContent)
                        .withString("revisionTime", revisionTime)
                        .withString("questionBean", JsonUtils.toJson(curQuestion))
                        .navigation();
            } else {
                if (TsdService.M_BLE_DEVICE == null) {
                    showNotConnectPenDialog();
                    return;
                }
                if (!ComUtil.isNetworkConnected()) {
                    ToastUtil.initToast("网络已断开，请先检查网络");
                    return;
                }
                ARouter.getInstance().build(ConstantArouter.PATH_GATHER_REVISIONDRAWACTIVITY)
                        .withInt("examId", examId)
                        .withInt("type", Constants.TYPE_1)
                        .withString("questionBean", JsonUtils.toJson(curQuestion))
                        .navigation();
            }

        } else if (mId == R.id.iv_phonetic_play_or_pause) {

            if (curQuestion != null && curQuestion.getVoiceComment() != null) {
                if ( !curQuestion.getVoiceComment().endsWith(Constants.VIDEO_FORMAT)) {
                    ToastUtil.initToast("该音频地址格式错误，无法播放");
                    return;
                }else {
                    playOrPause(iv_phonetic_play_or_pause, curQuestion.getVoiceComment(), false);
                }
            }

        } else if (mId == R.id.tv_revision_detail_screen) {

            switchScreen(true);

        } else if (mId == R.id.tv_revision_detail_content) {

            switchScreen(false);

        }
    }

    private void switchScreen(boolean showScreen) {
        if (showScreen) {
            tv_revision_detail_screen.setSelected(true);
            tv_revision_detail_content.setSelected(false);
            ll_revision_other_content.setVisibility(View.GONE);
            tv_write_and_speak.setVisibility(View.GONE);
            showScreenContent();
        } else {
            tv_revision_detail_screen.setSelected(false);
            tv_revision_detail_content.setSelected(true);
            ll_revision_other_content.setVisibility(View.VISIBLE);
            tv_write_and_speak.setVisibility(View.VISIBLE);
            showQuestionContent();
        }
    }

    /**
     * 显示我的作答
     *
     * @param frtv_my_answer
     * @param answer
     */
    private void showAnsweredTextView(FlexibleRichTextView frtv_my_answer, String answer) {
        frtv_my_answer.resetTextView();
        if (answer == null) {
            frtv_my_answer.setText("暂无作答");
        } else {
            String reLatex = FormulaUtil.reLatex(answer);
            StringBuilder sbAnswer = new StringBuilder();
            if (reLatex.endsWith(".png") || reLatex.endsWith(".jpg")) {
                sbAnswer.append("<img src=\"");
                sbAnswer.append(reLatex);
                sbAnswer.append("\"/>");
            } else {
                sbAnswer.append(reLatex);
            }
            LogUtils.e("showAnsweredTextView: =" + sbAnswer.toString());
            frtv_my_answer.setVisibility(View.VISIBLE);
            frtv_my_answer.setText(sbAnswer.toString());
        }

    }


    /**
     * 提示未连接蓝牙笔
     */
    private void showNotConnectPenDialog() {
        DialogXUtil.customDialogShow("您还未连接蓝牙笔,是否去连接？", new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {
                ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY)
                        .navigation();
            }

            @Override
            public void onListenDialogCancel() {

            }

            @Override
            public void onListenDialogClose() {

            }
        });
    }


    /**
     * 跳转错题下标
     *
     * @return
     */
    private int checkNextWrongQuestionIndex() {
        int pos = questionNo + 1;
        for (int i = questionNo + 1; i < questionListBeans.size(); i++) {
            if (questionListBeans.get(i).getIsRight() != null && questionListBeans.get(i).getIsRight() != 1) {
                pos = i;
                break;
            }
        }
        return pos;
    }


    private void updateSubmitTextView(int no) {
        if (no >= 0 && no < questionListBeans.size() - 1) {
            tv_next_question.setText(getString(R.string.gather_next_question));
            tv_next_question.setEnabled(true);
        } else if (no == questionListBeans.size() - 1) {
            tv_next_question.setText(getString(R.string.revision_submit));
            if (isRevision == 1) {
                tv_next_question.setText(getString(R.string.gather_revision_submited));
                tv_next_question.setEnabled(false);
            }

        }
    }


    /**
     * 删除订正内容
     */
    private void showDeleteRevisionDialog() {
        DialogXUtil.customDialogShow("您确定要删除订正内容吗？",
                "确定", "取消", new DialogXUtil.OnDialogXListen() {
                    @Override
                    public void onListenDialogOk() {
                        revisionAction = 0;
                        deleteRevisionReq();
                    }

                    @Override
                    public void onListenDialogCancel() {

                    }

                    @Override
                    public void onListenDialogClose() {

                    }
                });
    }

    public void showSubmitDialog() {
        DialogXUtil.waitDialogShow("正在提交订正...");
    }

    public void hideSubmitDialog() {
        DialogXUtil.waitDialogDismiss();
    }

    /**
     * 显示提交订正弹框
     */
    private void showSubmitRevisionDialog() {
        String tip = "已完成所有错题订正，确定要提交订正吗？";
        int num = getRevisionNum();
        if (num > 0) {
            tip = String.format("您还有%s道错题未订正，确定要提交订正吗?", num);
        }
        DialogXUtil.customDialogShow(tip,
                "提交", "取消", new DialogXUtil.OnDialogXListen() {
                    @Override
                    public void onListenDialogOk() {
                        showSubmitDialog();
                        submitRevision();
                    }

                    @Override
                    public void onListenDialogCancel() {

                    }

                    @Override
                    public void onListenDialogClose() {

                    }
                });
    }

    /**
     * 提交错题订正
     * 传学生
     */
    private void submitRevision() {
        RevisionQuestionReq req = new RevisionQuestionReq(studentExamId, 1, vos);
        getPresenter().revisionWrongQuestion(JsonUtils.toJson(req), false, false, false);
    }


    /**
     * 删除订正内容
     */
    private void deleteRevisionReq() {
        List<RevisionQuestionReq.RevisionBean> vos = new ArrayList<>();
        revisionBean.setRevisionContent("");
        revisionBean.setRevisionType(null);
        revisionBean.setRevisionTime(null);
        vos.add(revisionBean);
        RevisionQuestionReq req = new RevisionQuestionReq(null, 0, vos);
        submitRevisionWrongQuestionReq(JsonUtils.toJson(req));
    }


    /**
     * 删除订正数据库数据
     */
    private void deleteRevisionItem() {
        String pid = examId + "_" + studentExamAnswerId + "_" + questionId;
        QuestionRevisionItem item = DBUtils.getInstance(this).getQuestionRevisionByTag(pid);
        if (item != null) {
            deleteLocalFile(item.getLocalAudioPath(), item.getLocalTrackPath());
            DBUtils.getInstance(this).deleteQuestionRevisionItem(item);
        }
    }


    /**
     * 删除本地文件
     *
     * @param localAudioPath
     * @param localTrackPath
     */
    private void deleteLocalFile(String localAudioPath, String localTrackPath) {
        if (localAudioPath != null) {
            File audioFile = new File(localAudioPath);
            if (audioFile.exists()) {
                audioFile.delete();
            }
        }

        if (localTrackPath != null) {
            File trackFile = new File(localTrackPath);
            if (trackFile.exists()) {
                trackFile.delete();
            }
        }
    }

    /**
     * 删除本地数据
     * @param pid
     */


    /**
     * 播放音频
     * 讲解或批注
     *
     * @param view
     * @param explainUrl
     */
    private void playOrPause(ImageView view, String explainUrl, boolean isExplain) {
        if (view.getId() == R.id.iv_audio_play_or_pause) {
            iv_phonetic_play_or_pause.setImageResource(R.drawable.common_video_start);
            rsb_phonetic_progress.setProgress(0);
            if (curQuestion != null && curQuestion.getVoiceCommentDuration() != null) {
                tv_phonetic_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(curQuestion.getVoiceCommentDuration() * 1000)));
            } else {
                tv_phonetic_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(0)));
            }
        } else if (view.getId() == R.id.iv_phonetic_play_or_pause) {
            iv_audio_play_or_pause.setImageResource(R.drawable.common_video_start);
            rsb_audio_progress.setProgress(0);
            if (curExplainBean != null && curExplainBean.getVideoTime() != null) {
                tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(curExplainBean.getVideoTime() * 1000)));
            } else {
                tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(0)));
            }
        }
        LogUtils.e("playOrPause ==" + isExplainAudio);
        if (isExplainAudio == null) {
            startTimer = false;
            isExplainAudio = isExplain;
            AudioPlayerManager.getInstance(RevisionDetailActivity.this).changeAudioUrl(explainUrl);
        } else if (isExplainAudio != isExplain) {
            isExplainAudio = isExplain;
            startTimer = false;
            AudioPlayerManager.getInstance(RevisionDetailActivity.this).changeAudioUrl(explainUrl);
        } else {
            onPlayOrPause();
        }
    }


    /**
     * 播放或暂停
     */
    private void onPlayOrPause() {
        if (startTimer) {
            startTimer = false;
        }
        AudioPlayerManager.getInstance(this).playOrPause();
    }


    private void setPlayView(boolean playWhenRead) {
        if (playWhenRead) {
            if (isExplainAudio) {
                iv_audio_play_or_pause.setImageResource(R.drawable.common_video_pause);
            } else {
                iv_phonetic_play_or_pause.setImageResource(R.drawable.common_video_pause);
            }
        } else {
            iv_phonetic_play_or_pause.setImageResource(R.drawable.common_video_start);
            iv_audio_play_or_pause.setImageResource(R.drawable.common_video_start);
        }
    }


    /**
     * 更新音频时间
     *
     * @param duration
     */
    private void updateCurrentTime(long cur, long duration) {
        String audioTime;
        if (duration < 0 || cur == 0) {
            audioTime = String.format("%s/%s", "00:00", ComUtil.strToTime(duration / 1000 + ""));
        } else {
            double temp = (double) cur / 1000;
            audioTime = String.format("%s/%s", ComUtil.strToTime("" + (int) (Math.round(temp))), ComUtil.strToTime(duration / 1000 + ""));
        }
        //都没有在播放归0
        if ((isExplainAudio == null)) {
            rsb_audio_progress.setProgress(0);
            tv_audio_time.setText(audioTime);
            rsb_phonetic_progress.setProgress(0);
            tv_phonetic_time.setText(audioTime);
        } else if (isExplainAudio) {
            float pro = cur * rsb_audio_progress.getMaxProgress() / duration;
            rsb_audio_progress.setProgress(pro);
            tv_audio_time.setText(audioTime);
        } else {
            float pro = cur * rsb_phonetic_progress.getMaxProgress() / duration;
            rsb_phonetic_progress.setProgress(pro);
            tv_phonetic_time.setText(audioTime);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (AudioPlayerManager.getInstance(this).isPlaying()) {
            onPlayOrPause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.e("onStop start");

    }


    @Override
    protected void onDestroy() {
        LogUtils.e("onDestroy start");
        super.onDestroy();
        AudioPlayerManager.getInstance(RevisionDetailActivity.this).stop(false);
        AudioPlayerManager.getInstance(RevisionDetailActivity.this).release();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEventReceived(BaseEvent event) {
        if (event.getCode() == Constants.ConstData.REVISION_RECORD_FINISH) {
            //错题订正详情订正完一题就提交一次
            revisionAction = 1;
            List<RevisionQuestionReq.RevisionBean> vos = new ArrayList<>();
            revisionBean = (RevisionQuestionReq.RevisionBean) event.getData();
            vos.add(revisionBean);
            RevisionQuestionReq req = new RevisionQuestionReq(studentExamId, 0, vos);
            submitRevisionWrongQuestionReq(JsonUtils.toJson(req));
        }
    }

    /**
     * 提交订正请求
     *
     * @return
     */
    private void submitRevisionWrongQuestionReq(String reqData) {
        getPresenter().revisionWrongQuestion(reqData, false, false, true);
    }


    /**
     * 更新说写订正的视图
     */
    private void updateRevisionTextView() {
        tv_write_and_speak.setVisibility(View.VISIBLE);
        if (curQuestion == null) return;
        if (curQuestion.getIsRevision() != null && curQuestion.getIsRevision() == 1) {
            tv_write_and_speak.setText("已订正");
            tv_write_and_speak.setSelected(true);
            revisionContent = curQuestion.getRevisionContent();
            revisionTime = curQuestion.getRevisionTime();
            if (revisionBean == null) {
                revisionBean = new RevisionQuestionReq.RevisionBean(curQuestion.getStudentExamAnswerId(),
                        curQuestion.getQuestionId(), revisionContent, 2, revisionTime, 1, curQuestion.getSubjectId());
            }
        } else {
            tv_write_and_speak.setText("说写订正");
            tv_write_and_speak.setSelected(false);
        }
    }


    /**
     * 获取错题订正的数量
     *
     * @return
     */
    private int getRevisionNum() {
        int notRevisionNo = 0;
        List<RevisionExamQuestionInfo.Data.QuestionListBean> wrongList = new ArrayList<>();
        for (RevisionExamQuestionInfo.Data.QuestionListBean bean : questionListBeans) {
            if (bean.getIsRight() != null && bean.getIsRight() != 1) {
                wrongList.add(bean);
            }
        }

        for (int i = 0; i < wrongList.size(); i++) {
            if (wrongList.get(i).getIsRevision() == 0) {
                notRevisionNo++;
            }
        }
        return notRevisionNo;
    }

    @Override
    public void onCurrentPosition(Bundle bundle) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setCurAndTotalView(bundle);
            }
        });
    }

    private void setCurAndTotalView(Bundle bundle) {
        long cur = bundle.getLong(AudioPlayerManager.STR_CURRENT_POSITION);
        long dur = bundle.getLong(AudioPlayerManager.STR_DURATION);
        if (dur < 0 || cur == 0) return;
        updateCurrentTime(cur, dur);
    }

}
